package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.core.constant.enums.AllAuditActionStatusEnum;
import com.engine4cloud.tdf.common.core.constant.enums.AuditBusinessTypeEnum;
import com.engine4cloud.tdf.common.core.constant.enums.CorFileTypeEnum;
import com.engine4cloud.tdf.common.core.constant.enums.NormalAuditActionStatusEnum;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.core.util.lambda.Actions;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.SpChangePlaceConvert;
import com.engine4cloud.tdf.supervision.dto.create.SpAuditActionResultCreateDTO;
import com.engine4cloud.tdf.supervision.dto.create.SpChangePlaceCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.JzdxAreaQueryDTO;
import com.engine4cloud.tdf.supervision.dto.query.JzdxFileQueryDTO;
import com.engine4cloud.tdf.supervision.dto.query.SpChangePlaceQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxAreaResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.SpChangePlaceResult;
import com.engine4cloud.tdf.supervision.dto.update.SpChangePlaceUpdateDTO;
import com.engine4cloud.tdf.supervision.dto.update.SpNormalPreActionUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.SpChangePlaceEntity;
import com.engine4cloud.tdf.supervision.mapper.SpChangePlaceMapper;
import com.engine4cloud.tdf.supervision.service.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.Optional;

/**
 * 执行地变更信息采集表
 *
 * @author wenjie
 * @date 2024-04-10 11:04:52
 */
@Service
public class SpChangePlaceServiceImpl extends ServiceImpl<SpChangePlaceMapper, SpChangePlaceEntity> implements SpChangePlaceService {

    @Resource
    private JzdxService jzdxService;

    @Resource
    private JzdxAreaService areaService;

    @Resource
    private SpAuditResultService auditResultService;

    @Resource
    private JzdxFileService fileService;

    @Override
    public PageInfo<SpChangePlaceResult> pageList(SpChangePlaceQueryDTO dto) {
        IPage<SpChangePlaceEntity> page = super.page(Pages.page(dto), wrapper(dto));
        return Pages.convert(page, SpChangePlaceConvert.INSTANCE::convertCategory);
    }

    @Override
    public SpChangePlaceResult getByBatch(String batch) {
        return SpChangePlaceConvert.INSTANCE.convert(super.getOne(wrapper(new SpChangePlaceQueryDTO(batch))));
    }

    @Override
    public void changeAction(SpNormalPreActionUpdateDTO dto) {
        SpChangePlaceEntity entity = Optional.ofNullable(this.getOne(wrapper(new SpChangePlaceQueryDTO(dto.getRybh(), dto.getLcbh()))))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        entity.setPreAction(dto.getAction());
        super.updateById(entity);
    }

    @Override
    public SpChangePlaceResult getById(Long id) {
        SpChangePlaceResult result = Optional.ofNullable(SpChangePlaceConvert.INSTANCE.convert(super.getById(id)))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));
        //设置法律文书信息
        this.setInstrumentList(result);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(SpChangePlaceCreateDTO dto) {
        JzdxResultDTO dx = Optional.ofNullable(jzdxService.getByCode(dto.getRybh()))
                .orElseThrow(() -> new ValidateCodeException("矫正对象数据不存在"));

        TdfUser user = SecurityUtils.getUser();
        SpChangePlaceEntity entity = SpChangePlaceConvert.INSTANCE.create(dto, dx.getTenantId(), NormalAuditActionStatusEnum.CREATE);
        //设置执行地地区信息
        this.setArea(entity);
        //保存主体信息
        super.save(entity);
        //保存文件信息
        this.saveInstrumentList(dto, entity, user);
        //保存审核信息
        return auditResultService.create(
                new SpAuditActionResultCreateDTO(
                        entity.getRybh(),
                        entity.getLcbh(),
                        "",
                        AuditBusinessTypeEnum.CHANGE_PLACE,
                        AllAuditActionStatusEnum.CREATE,
                        user.getUsername(),
                        entity.getTenantId(),
                        user.getDeptId()
                ));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(SpChangePlaceUpdateDTO dto) {
        SpChangePlaceEntity old = Optional.ofNullable(super.getById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        TdfUser user = SecurityUtils.getUser();
        SpChangePlaceEntity entity = SpChangePlaceConvert.INSTANCE.update(dto);
        //保存执行地目的地
        this.setArea(entity);
        //保存主体信息
        super.updateById(entity);
        //保存文件信息
        this.updateInstrumentList(dto, old, user);
        return true;
    }

    private void setArea(SpChangePlaceEntity entity) {
        JzdxAreaResultDTO area = areaService.getArea(new JzdxAreaQueryDTO(entity.getQrdszs(), entity.getQrdszd(), entity.getQrdszx(), Objects.isNull(entity.getQrdxz()) ? null : Long.parseLong(entity.getQrdxz())));
        entity.setQrdszsmc(area.getProvince().getName());
        entity.setQrdszdmc(area.getCity().getName());

        Actions.apply(Objects.nonNull(area.getCounty()), () -> entity.setQrdszxmc(area.getCounty().getName()));
        Actions.apply(Objects.nonNull(area.getVillage()), () -> entity.setQrdxzmc(area.getVillage().getName()));
    }

    public void saveInstrumentList(SpChangePlaceCreateDTO dto, SpChangePlaceEntity entity, TdfUser user) {
        fileService.batchSaveFile(new JzdxFileQueryDTO(entity.getRybh(), entity.getLcbh(), CorFileTypeEnum.CORRECTOR_CHANGE_PLACE), dto.getInstrumentList(), user);
    }

    public void updateInstrumentList(SpChangePlaceUpdateDTO dto, SpChangePlaceEntity entity, TdfUser user) {
        fileService.batchUpdateFile(new JzdxFileQueryDTO(entity.getRybh(), entity.getLcbh(), CorFileTypeEnum.CORRECTOR_CHANGE_PLACE), dto.getInstrumentList(), user);
    }

    private void setInstrumentList(SpChangePlaceResult dto) {
        JzdxFileQueryDTO query = new JzdxFileQueryDTO(dto.getRybh(), dto.getLcbh(), CorFileTypeEnum.CORRECTOR_CHANGE_PLACE);
        dto.setInstrumentList(fileService.findList(query));
    }

    private LambdaQueryWrapper<SpChangePlaceEntity> wrapper(SpChangePlaceQueryDTO query) {
        LambdaQueryWrapper<SpChangePlaceEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(SpChangePlaceEntity::getId, v));
        Queries.accept(query.getRybh(), v -> wrapper.eq(SpChangePlaceEntity::getRybh, v));
        Queries.accept(query.getLcbh(), v -> wrapper.eq(SpChangePlaceEntity::getLcbh, v));
        Queries.accept(query.getPreAction(), v -> wrapper.eq(SpChangePlaceEntity::getPreAction, v));
        return wrapper;
    }
}